#include "stdafx.h"
#include "KtvDataRecord.h"

CKtvDataRecord::CKtvDataRecord(void)
{
	buf = NULL;
	size = 0;
}

CKtvDataRecord::~CKtvDataRecord(void)
{
	Free();
}

void  CKtvDataRecord::Free(void)
{
	if( buf )
	{
		delete[] buf;
		buf = NULL;
	}

	size = 0;

}

void  CKtvDataRecord::Clear(void)
{
	Free();
}

void  CKtvDataRecord::Zero(void)
{
	if( buf && size )
		memset( buf, 0, size+ KTV_DATA_RECORD_EXT_SIZE );
}

BOOL  CKtvDataRecord::LoadFile( LPCTSTR lpszFilePath )
{
	Free( );

	if( lpszFilePath == NULL )
		return FALSE;

	//CFile  cf;
	DWORD dwBytes = 0;
	HANDLE hFile = INVALID_HANDLE_VALUE;
	hFile = CreateFile(lpszFilePath, GENERIC_READ, /*0*/FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);

	if( hFile != INVALID_HANDLE_VALUE )
	{
		this->size = GetFileSize( hFile, NULL );
		if( this->size > 0 )
		{
			Alloc( size );			
			if( this->buf )
			{
				Zero( );
				ReadFile( hFile,  this->GetBuffer(), this->size, &dwBytes, NULL );
			}
		}

		CloseHandle(hFile);
		return TRUE;
	}

	return FALSE;
}

BYTE* CKtvDataRecord::GetBuffer(void)
{
	return buf;
}

DWORD CKtvDataRecord::GetSize(void)
{
	return size;
}

BOOL  CKtvDataRecord::IsEmpty(void)
{
	if( buf == NULL || size == 0 )
		return TRUE;
	else
		return FALSE;
}

void  CKtvDataRecord::Alloc( DWORD dwNewSize )
{
	if( buf == NULL )
	{
		this->buf = (BYTE*)malloc( dwNewSize+KTV_DATA_RECORD_EXT_SIZE );
		this->size = dwNewSize;
		Zero();
	}
	else
	{
		this->buf = (BYTE*)realloc( (void*)buf, dwNewSize+KTV_DATA_RECORD_EXT_SIZE );
		this->size = dwNewSize;
	}

}

void  CKtvDataRecord::SetLength(DWORD dwNewSize)
{
	Alloc( dwNewSize );
}

//////////////////////////////////////////////////////////////////////////



